//
//  ShowDetailViewController.m
//  demoapp
//
//  Created by MingmingSun on 15/9/5.
//  Copyright (c) 2015年 pingplusplus. All rights reserved.
//

#import "ShowDetailViewController.h"
#import "PullingRefreshTableView.h"
#import "UIImageView+AFNetworking.h"
#import "ShowReplyViewController.h"
#import "ShowCommitView.h"
#import "KGModal.h"
#import "tooles.h"

@interface ShowDetailViewController ()<UITableViewDataSource,UITableViewDelegate,PullingRefreshTableViewDelegate,ShowCommitDelegate>

@property(nonatomic,strong) NSDictionary *showDic;
@property(nonatomic,strong) NSMutableArray *barberArray;
@property(nonatomic,weak) IBOutlet PullingRefreshTableView *listView;
@property(assign,nonatomic) BOOL refreshing;
@property(assign,nonatomic) NSInteger page;

@property(nonatomic,weak) UIScrollView *mainScrollView;
@property(nonatomic,assign) int timeCount;

@end

@implementation ShowDetailViewController

@synthesize listView;
@synthesize mainScrollView;
@synthesize timeCount;
@synthesize refreshing = _refreshing;
@synthesize page = _page;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"晒单详情";
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:@"回复"
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(rightBarPressed:)];
        self.showDic = nil;
        self.barberArray = [NSMutableArray array];
        self.timeCount = 0;
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBarPressed:(id)sender{
    ShowCommitView *timeView = [[ShowCommitView alloc] init];
    timeView.myDelegate = self;
    [[KGModal sharedInstance] showWithContentView:timeView andAnimated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    _refreshing = YES;
    self.listView.pullingDelegate = self;
    [self.listView awakeWhenXIB:self.listView.frame];
    [self getShowLists];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getShowLists{
    //    customer - 客户id，可缺省。缺省表示不限制，customer<=0取当前用户的晒单。
    NSDictionary *para =
    @{@"id":APPALL.showID,
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"show_index" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    self.showDic = [aSucData objectForKey:@"show"];
                    [self getShowReplys];
//                    [_showArray removeAllObjects];
//                    NSArray *cityArray = [aSucData objectForKey:@"show"];
//                    for (NSDictionary *dic in cityArray) {
//                        [_showArray addObject:dic];
//                    }
//                    [_collectionView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (void)getShowReplys {
    NSDictionary *para =
    //    @{@"type":@"history",
    @{@"id":APPALL.showID,
      @"max":@"10",
      @"offset":[NSString stringWithFormat:@"%i",_page * 10],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"show_listReply" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        [self.listView tableViewDidFinishedLoading];
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    NSLog(@"yeah1....");
                    if(_refreshing){
                        [_barberArray removeAllObjects];
                    }
                    NSArray *cityArray = [aSucData objectForKey:@"reply"];
                    for (NSDictionary *dic in cityArray) {
                        [_barberArray addObject:dic];
                    }
                    [listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

//listReply

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return self.showDic?2:0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
        case 1:
            return self.barberArray.count;
        default:
            return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return 300.0f;
        case 1:{
            NSDictionary *replyDic = [self.barberArray objectAtIndex:indexPath.row];
            return [ShowDetailViewController getReplyHeight:replyDic];
        }
        default:
            return 0;
    }
}

+(CGFloat)getReplyHeight:(NSDictionary*)aDic{
    int baseHeight = 80;
    if([aDic objectForKey:@"rreplys"]){
        NSArray *array = [aDic objectForKey:@"rreplys"];
        if(array.count){
            baseHeight += 40;
        }
    }
    return baseHeight;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    switch (indexPath.section) {
        case 0:{
            inde= @"ShowReplyID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowReplyCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
            UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
            UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
            UIImageView *img1 = (UIImageView*)[cell viewWithTag:99];
            self.mainScrollView = (UIScrollView*)[cell viewWithTag:98];
            UIPageControl *pgcrl3 = (UIPageControl*)[cell viewWithTag:97];
            pgcrl3.hidden = YES;
            lab1.text = [tooles replaceNullFromDic:self.showDic withKeyArray:@[@"customer",@"name"]];
            lab2.text = [tooles replaceNullFromDic:self.showDic withKeyArray:@[@"submitDate"]];
            lab3.text = [NSString stringWithFormat:@"%i人喜欢",[[self.showDic valueForKey:@"praise"] integerValue]];
            lab4.text = [NSString stringWithFormat:@"%i条评论",[[self.showDic valueForKey:@"replyNum"] integerValue]];
            NSString *headImage = [[self.showDic objectForKey:@"customer"] valueForKey:@"headImage"];
            if(![headImage isEqual:[NSNull null]]
               && headImage
               && headImage.length){
                [img1 setImageWithURL:[NSURL URLWithString:headImage] placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
            }
            int i = 0;
            NSArray *picArray = @[@"mainPic",@"sidePic",@"backPic",@"otherPic"];
            for(UIView *v in self.mainScrollView.subviews){
                [v removeFromSuperview];
            }
            self.mainScrollView.pagingEnabled = YES;
            for(NSString *cacheStr in picArray){
                if([[self.showDic objectForKey:cacheStr] isEqual:[NSNull null]])
                    continue;
                if(![self.showDic objectForKey:cacheStr])
                    continue;
                headImage = [[self.showDic objectForKey:cacheStr] valueForKey:@"url"];
                if((![headImage isEqual:[NSNull null]])
                   && headImage
                   && headImage.length){
                    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(300 * i,0,300, 210)];
                    [img setImageWithURL:[NSURL URLWithString:headImage] placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
                    img.contentMode = UIViewContentModeScaleAspectFit;
                    [self.mainScrollView setContentSize:CGSizeMake(300 * (i + 1), 210)];
                    [self.mainScrollView addSubview:img];
                    i++;
                }
            }
        }
            break;
        case 1:{
            inde= @"ShowHeadID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ShowHeadCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
            UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
            UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
            UILabel *lab5 = (UILabel*)[cell viewWithTag:5];
            lab5.hidden = NO;
            UIImageView *img1 = (UIImageView*)[cell viewWithTag:99];
            NSDictionary *replyDic = [self.barberArray objectAtIndex:indexPath.row];
            lab2.text = [tooles replaceNullFromDic:replyDic withKeyArray:@[@"replyDate"]];
            lab3.text = [tooles replaceNullFromDic:replyDic withKeyArray:@[@"content"]];
            NSString *lab4Str = @"";
            if([replyDic objectForKey:@"rreplys"]){
                NSArray *array = [replyDic objectForKey:@"rreplys"];
                if(array.count){
                    NSDictionary *arDic = [array firstObject];
                    lab4Str = [NSString stringWithFormat:@"%@:%@",[tooles replaceNullFromDic:arDic withKeyArray:@[@"customer"]],[tooles replaceNullFromDic:arDic withKeyArray:@[@"content"]]];
                }
            }
            if(lab4Str.length){
                lab4.text = lab4Str;
                lab4.hidden = NO;
                lab5.frame = CGRectMake(272, 100, 40, 20);
            }else{
                lab4.hidden = YES;
                lab5.frame = CGRectMake(272, 60 , 40, 20);
            }
            lab1.text = [tooles replaceNullFromDic:replyDic withKeyArray:@[@"customer",@"name"]];
            NSString *headImage = [[replyDic objectForKey:@"customer"] valueForKey:@"headImage"];
            if((![headImage isEqual:[NSNull null]])
               && headImage
               && headImage.length){
                [img1 setImageWithURL:[NSURL URLWithString:headImage] placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
            }
        }
            break;
        default:
            break;
    }
    return cell;
}

-(void)scrollTimer{
    timeCount ++;
    int PAGENUM = self.mainScrollView.contentSize.width/300.0f;
    if (timeCount >= PAGENUM) {
        timeCount = 0;
    }
    [mainScrollView scrollRectToVisible:CGRectMake(timeCount * 300.0,0, 300.0, 210.0) animated:YES];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section < 1)
        return;
    NSDictionary *replyDDic = [self.barberArray objectAtIndex:indexPath.row];
    ShowReplyViewController *vc = [[ShowReplyViewController alloc] initWithReplyDic:replyDDic];
    vc.myDelegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    self.page = 0;
    [self getShowLists];
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    self.refreshing = NO;
    self.page++;
    [self getShowReplys];
}

-(void)showPressed:(id)sender{
    self.refreshing = YES;
    self.page = 0;
    [self getShowLists];
    [[KGModal sharedInstance] hideAnimated:YES];
}

#pragma mark - Scroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.listView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.listView tableViewDidEndDragging:scrollView];
}

@end